local snow    = require("meet_your_mods.mhr").snow
local status  = require("meet_your_mods.status")
local setting = require("meet_your_mods.setting")
local ui      = require("meet_your_mods.ui")
local input   = require("meet_your_mods.input")

local miscellaneous = {
    setting       = {
        hide_otomo          = true, --只显示自己的随从
        simple_whish_list   = true, --隐藏分类素材集齐提示
        no_network_error    = true, --在任务中隐藏网络错误对话框
        auto_index_handbook = true, --自动索引猎人手册
    },
    message       = {
        [status.languages.japanese]            = "通信エラーが発生しました",
        [status.languages.english]             = "A communication error has occurred",
        [status.languages.chinese_troditional] = "發生通訊錯誤",
        [status.languages.chinese_simplified]  = "发生连接错误",
    },
    monster_index = 0,
    monsters      = nil,
    otomos        = {},
}

--隐藏分类素材集齐提示
function miscellaneous:pre_reqAddChatWishListCreatable(parameters)
    if self.setting.simple_whish_list and sdk.to_int64(parameters[4]) ~= 0 then
        return sdk.PreHookResult.SKIP_ORIGINAL
    end
    return sdk.PreHookResult.CALL_ORIGINAL
end

--关闭网络错误对话框
function miscellaneous:pre_setOpenNetworkErrorWindowSelection(_)
    if self.setting.no_network_error
        and status.logical_status.quest == status:current_status()
    then
        snow.gui.ChatManager:get_singleton():reqAddChatInfomation(self.message[status:display_language()]
            or self.message[status.languages.default], 2289944406)
        return sdk.PreHookResult.SKIP_ORIGINAL
    end

    return sdk.PreHookResult.CALL_ORIGINAL
end

--获取当前任务的目标怪物列表
function miscellaneous:update_quest_monsters()
    if self.monsters then
        return self.monsters
    end

    local quest_data = snow.QuestManager:get_singleton():getActiveQuestData()
    if not quest_data then
        return nil
    end

    local normal_data  = quest_data:get_RawNormal()
    local mystery_data = quest_data:get_RandomMystery()
    if normal_data then
        self.monsters = {}
        if snow.quest.QuestTargetType.AllMainEnemy == normal_data._TargetType[1] then
            for _, monster in pairs(normal_data._BossEmType) do
                if monster ~= snow.enemy.EnemyDef.EmTypes.EmTypeNoData then
                    table.insert(self.monsters, monster)
                end
            end
        else
            for _, monster in pairs(normal_data._TgtEmType) do
                if monster ~= snow.enemy.EnemyDef.EmTypes.EmTypeNoData then
                    table.insert(self.monsters, monster)
                end
            end
        end
    elseif mystery_data then
        self.monsters = {}
        for index = 1, mystery_data._HuntTargetNum do
            table.insert(self.monsters, mystery_data._BossEmType[index])
        end
    end

    if self.monsters and 0 == #self.monsters then
        self.monsters = nil
    end
    return self.monsters
end

function miscellaneous:post_questActivate(result)
    if self.setting.auto_index_handbook then
        self.monsters = nil
        self:update_quest_monsters()
    end

    return result
end

function miscellaneous:post_questCancel(result)
    self.monsters = nil
    return result
end

--自动索引猎人手册
function miscellaneous:pre_doOpen(parameters)
    if self.setting.auto_index_handbook then
        self.monster_index = 0
    end
end

function miscellaneous:pre_update(parameters)
    if not self.setting.auto_index_handbook
        or not self:update_quest_monsters()
    then
        return sdk.PreHookResult.CALL_ORIGINAL
    end

    local gui = snow.gui.GuiMonsterList(sdk.to_managed_object(parameters[2]))
    if gui._ListType ~= snow.gui.GuiMonsterList.ListType.Boss
        or not input:ui_andTrg(snow.StmInputManager.UI_INPUT.STATIC_MENU_ACT_TYPE_CL)
    then
        return sdk.PreHookResult.CALL_ORIGINAL
    end

    self.monster_index = self.monster_index + 1
    for index, monster in pairs(gui._MonsterList) do
        if self.monsters[self.monster_index % #self.monsters + 1] == monster._Data._EmType then
            local list_ctrl = gui._MonsterListScrollCtrl
            local selected  = list_ctrl:get_selectedIndex()

            selected._HasValue = true
            selected._Value    = index - 1
            list_ctrl:set_selectedIndex(selected:get_instance())

            snow.gui.SnowGuiCommonUtility:reqSe(4105602971)
            gui:updateTopTab()
            list_ctrl:selectedIndexToCursorSelect()
            gui:setupMainPage(false, true)
            gui:updateMainPage(true)
            return sdk.PreHookResult.CALL_ORIGINAL
        end
    end

    return sdk.PreHookResult.CALL_ORIGINAL
end

--读取其他人的随从
function miscellaneous:load_otomos()
    self.otomos = {}
    local otomos = snow.otomo.OtomoManager:get_singleton().OtomoObject
    for _, index in pairs({2, 3, 4, 6, 7, 8}) do
        local otomo = otomos[index]
        if otomo then
            table.insert(self.otomos, { otomo = otomo, object = otomo:get_GameObject(), })
        end
    end
end

function miscellaneous:hide_otomos()
    if not self.setting.hide_otomo then
        return
    end

    for _, otomo in pairs(self.otomos) do
        if otomo.otomo:get_RideState() ~= snow.otomo.OtomoDef.DogRideState.Ridding then
            otomo.object:set_DrawSelf(false)
        end
    end
end

function miscellaneous:initialize()
    re.on_application_entry("PrepareRendering", function() self:hide_otomos() end)

    snow.QuestManager.questStart:sdk_hook(function() self:load_otomos() end)
    snow.QuestManager.onQuestEnd:sdk_hook(function() self.otomos = {} end)

    snow.gui.ChatManager.reqAddChatWishListCreatable:sdk_auto_hook(self)
    snow.gui.GuiManager.setOpenNetworkErrorWindowSelection:sdk_auto_hook(self)
    snow.QuestManager.questActivate:sdk_auto_hook(self)
    snow.QuestManager.questCancel:sdk_auto_hook(self)
    snow.gui.GuiMonsterList.doOpen:sdk_auto_hook(self)
    snow.gui.GuiMonsterList.update:sdk_auto_hook(self)

    setting:bind_setting("miscellaneous", self.setting)

    ui:cluster("gui", "UI增强")
    ui:checkbox("gui", "miscellaneous", "hide_otomo", "只显示自己的随从")
    ui:checkbox("gui", "miscellaneous", "simple_whish_list", "隐藏分类素材集齐提示")
    ui:checkbox("gui", "miscellaneous", "no_network_error", "在任务中隐藏网络错误对话框")
    ui:checkbox("gui", "miscellaneous", "auto_index_handbook", "自动索引猎人手册")
end

function miscellaneous:normalize()
    if status.logical_status.quest == status:current_status() then
        self:load_otomos()
    end
end

return miscellaneous
